// pages/serverMyInformation/serverMyInformation.js
//获取应用实例
var common = require("../../../utils/common.js");
var sign = require('../../../utils/lib/sign.js');
var dict = require('../../../utils/dict.js');
const qiniuUploader = require("../../../utils/lib/qiniuUploader.js");
const app = getApp();
//引入模板 改变底部菜单颜色值方法
import tempObj from '../../template/BottomTab.js'
var a = tempObj.changeColor
Page({
  changeColor: a,

  /**
	 * 页面的初始数据
	 */
  data: {
    tabBars: {
      left: {
        url: '../../order/list/list',
        icon: '../../img/apply.png',
        text: "招聘头条",

      },
      right: {
        url: '../index/index',
        icon: '../../img/mine.png',
        text: "我的",

      },
    },
    genderItems: [
      { name: '男', value: '1', },
      { name: '女', value: '2', },
    ],
    hasCertData: [
      { name: '有', value: '1' },
      { name: '无', value: '2', },
    ],
    hasCert: false,
    resume: {},
    mobile: "",
    serviceTypes: [],
    workYear: [],
    serverArea: [],
    region: ['', ''],
    serviceCanDate: "",
    sex: "",
    serviceTypeIds: "",
    workYearId: "",
    remark:'',

    certData: [
      // { id: 0, certName: '', certImgs: '' },
    ],
    headImg: {},        // { isSelect : false, file : }
    liveImgs: {},       // { isSelect : false, file : [] }
    idCardFrontImg: {}, // { isSelect : false, file : }
    idCardBackImg: {},  // { isSelect : false, file : }
    videoUrl: "",
    videoTokenUrl: "",
    upToken: "",
    chooseVideoFile: ""
  },

  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function (options) {
    this.setData({
      "tabBars.currentIndex": app.globalData.currentIndex
    })
    console.log("onload");

    var that = this;
    that.loadResumeData();
  },
  //=================================初始化数据方法==
  loadResumeData: function () {
    var that = this;
    var params = {};
    params.resumeNo = wx.getStorageSync("resumeNo");
    params.mobile = wx.getStorageSync("mobile");
    params = sign.getSignParams(params)
    wx.request({
      url: app.globalData.baseUrl + '/api/resume/detail.json',
      data: params,
      success: function (res) {
        var result = res.data;
        var videos = [];
        if (result.status == 0) {

          var resume = result.data;
          that.initFormData(resume);
          console.log(resume);

          wx.setStorage({
            key: 'resume',
            data: result.data,
          })
        }
      },

    })
  },

  initFormData: function (resume) {
    var that = this;
    that.setData({ resume: resume })

    //头像
    var headImg = { isSelect: false, file: resume.headImg }
    that.setData({ headImg: headImg })

    //籍贯
    var hukou = resume.hukou;
    if (!common.isEmpty(hukou)) {
      that.setData({ region: hukou.split(" ") });
    }

    //空档期
    that.setData({ serviceCanDate: resume.serviceCanDate });

    //自我介绍
    that.setData({ remark: resume.remark}) 

    //性别
    that.setData({ sex: resume.sex });

    //技能勾选
    var hasCert = false;
    if (resume.hasCert == 1) hasCert = true;
    if (hasCert) {
      that.data.hasCertData[0].checked = true;
    } else {
      that.data.hasCertData[1].checked = true;
    }
    this.setData({ hasCertData: that.data.hasCertData, hasCert: hasCert });

    //生活照片
    var liveImgs = [];
    if (!common.isEmpty(resume.resumeResource)) {
      for (var i = 0; i < resume.resumeResource.length; i++) {
        var img = resume.resumeResource[i];
        if (img.resourceType == "resume_live_img") {
          liveImgs.push(img.resourceUrl);
        }

        if (img.resourceType == "id_card_front_img") {
          //身份证正面
          var img = { isSelect: false, file: img.resourceUrl }
          this.setData({ idCardFrontImg: img });
        }

        if (img.resourceType == "id_card_back_img") {
          //身份证反面
          var img = { isSelect: false, file: img.resourceUrl }
          this.setData({ idCardBackImg: img });
        }

        //视频文件
        if (img.resourceType == "resume_video") {
          that.getVideoUrlToken(img.resourceUrl)
        }
      }
      var imgs = { isSelect: false, file: liveImgs }
      this.setData({ liveImgs: imgs });
    }

    //证书
    var certData = [];
    if (!common.isEmpty(resume.resumeCerts)) {
      for (var i = 0; i < resume.resumeCerts.length; i++) {
        var item = resume.resumeCerts[i];
        var certDataItem = {};
        certDataItem.id = item.id;
        certDataItem.certName = item.certName;
        certDataItem.certImgs = item.certImg;
        certData.push(certDataItem);
      }
      this.setData({ certData: certData });
    }

    dict.getDict("service_type", "", that.initDictServiceType);
    dict.getDict("work_year", "", that.initDictWorkYear);
    dict.getDict("region", 4780, that.initDicServiceArea);

  },


  initDictServiceType: function (res) {
    var that = this;
    var serviceTypeIds = that.data.resume.serviceTypeIds;
    var list = res;
    for (var i = 0; i < list.length; i++) {
      var t = list[i];
      if (serviceTypeIds.indexOf(t.id) >= 0) {
        list[i].checked = true;
      }
    }
    that.setData({ serviceTypes: list })
  },

  initDictWorkYear: function (res) {
    var that = this;
    var workYear = that.data.resume.workYear;
    var list = res;
    for (var i = 0; i < list.length; i++) {
      var t = list[i];
      if (workYear == t.id) {
        list[i].checked = true;
      }
    }
    that.setData({ workYear: list })
  },

  initDicServiceArea: function (res) {
    var that = this;

    var serviceArea = that.data.resume.regionIds;
    var list = res;
    for (var i = 0; i < list.length; i++) {
      var t = list[i];
      if (serviceArea.indexOf(t.id) >= 0) {
        list[i].checked = true;
      }
    }


    that.setData({ serverArea: list })
  },

  //=================================change事件方法
  /**
	 * 选择籍贯
	 */
  bindRegionChange: function (e) {
    var that = this;
    console.log('picker发送选择改变，携带值为', e.detail.value);
    that.setData({ region: e.detail.value })
  },

  /**
	 * 日期控件
	 */
  bindDateChange: function (e) {
    this.setData({ serviceCanDate: e.detail.value })
  },

  genderChange: function (e) {
    var checked = e.detail.value;
    this.setData({ sex: checked });
  },

  serviceTypeChange: function (e) {
    var checked = e.detail.value;
    var changed = {}
    for (var i = 0; i < this.data.serviceTypes.length; i++) {

      var id = this.data.serviceTypes[i].id;
      if (checked.indexOf(id.toString()) !== -1) {

        this.data.serviceTypes[i].checked = true;
      } else {
        this.data.serviceTypes[i].checked = false;
      }
    }
    this.setData({ serviceTypes: this.data.serviceTypes });

  },

  workYearChange: function (e) {
    var checked = e.detail.value;
    var changed = {}
    for (var i = 0; i < this.data.workYear.length; i++) {

      var id = this.data.workYear[i].id;
      if (checked.indexOf(id.toString()) !== -1) {

        this.data.workYear[i].checked = true;
      } else {
        this.data.workYear[i].checked = false;
      }
    }
    this.setData({ workYear: this.data.workYear });

  },

  serverAreaChange: function (e) {
    var checked = e.detail.value;
    var changed = {}
    for (var i = 0; i < this.data.serverArea.length; i++) {

      var id = this.data.serverArea[i].id;
      if (checked.indexOf(id.toString()) !== -1) {

        this.data.serverArea[i].checked = true;
      } else {
        this.data.serverArea[i].checked = false;
      }
    }
    this.setData({ serverArea: this.data.serverArea });

  },

  certChange: function (e) {
    var checked = e.detail.value;

    for (var i = 0; i < this.data.hasCertData.length; i++) {

      var v = this.data.hasCertData[i].value;
      if (checked == v) {
        this.data.hasCertData[i].checked = true;
      } else {
        this.data.hasCertData[i].checked = false;
      }
    }

    var hasCert = false;
    if (checked == 1) hasCert = true;
    this.setData({ hasCertData: this.data.hasCertData, hasCert: hasCert });
  },

  /**
   * 鼠标移开改变证书名称，并验证
   */
  certNameChange: function (e) {
    var that = this;
    // debugger
    // that.changeData('certificate', e.detail.value);
    var data = that.data.certData;
    var index = e.currentTarget.dataset.index;
    data[index].certName = e.detail.value;
    that.setData({
      certData: data
    })
  },

  /**
	 * 增加更多证书
	 * 
	 */
  addCertificate: function () {
    var obj = { name: "", imgSrc: "" };
    this.data.certData.push(obj);
    this.setData({
      certData: this.data.certData
    })
  },
  /**
   * 删除证书
   */
  deleteCertificate:function(e){
    var that=this;
    console.log(that.data.certData);
    var deleteIndex = e.currentTarget.dataset.index;
    var arrayCer = that.data.certData;
    var name = arrayCer[deleteIndex].certName;
    var resumeNo = wx.getStorageSync("resumeNo");
    var id = arrayCer[deleteIndex].id;
    var dataCer={
      resumeNo: resumeNo,
      id: id,
    }
    var dataCerParams=sign.getSignParams(dataCer);
    if (!(name==null || name==''|| name== undefined)){
      wx.showModal({
        title: '提示',
        content: '确定删除？',
        success: function (res) {
          if (res.confirm) {
            wx.request({
              url: app.globalData.baseUrl + '/api/resume/cert_del.json',
              data: dataCerParams,
              header: {
                "Content-Type": "application/x-www-form-urlencoded"
              },
              method: 'POST',
              success: function (response) {
                if (response.data.status == 0){
                  that.data.certData.splice(deleteIndex,1);
                  that.setData({
                    certData: that.data.certData,
                  })
                }
                console.log(response);
              }
            })
          } 
        }
      })

    }else{
      that.data.certData.splice(deleteIndex, 1);
      that.setData({
        certData: that.data.certData,
      })

    }

 
  },

  //==============================图片类操作
  headImgSelect: function (e) {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var headImg = {};
        headImg.isSelect = true;
        headImg.file = tempFilePaths;
        console.log(headImg);
        that.setData({ headImg: headImg });
      }
    })
  },

  certImgSelect: function (e) {

    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var data = that.data.certData;
        var index = e.currentTarget.dataset.index;
        data[index].certImgs = tempFilePaths;
        data[index].id = 0;
        that.setData({ certData: data });
      }
    })
  },

  liveImgSelect: function (e) {
    var that = this;
    wx.chooseImage({
      count: 5, // 默认9
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var liveImgs = {};
        liveImgs.isSelect = true;
        liveImgs.file = tempFilePaths;
        that.setData({ liveImgs: liveImgs });
      }
    })
  },

  idCardFrontImgSelect: function (e) {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var imgs = {};
        imgs.isSelect = true;
        imgs.file = tempFilePaths;
        that.setData({ idCardFrontImg: imgs });
      }
    })
  },

  idCardBackImgSelect: function (e) {
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var imgs = {};
        imgs.isSelect = true;
        imgs.file = tempFilePaths;
        that.setData({ idCardBackImg: imgs });
      }
    })
  },

  clickImage: function (e) {
    var that = this;
    var urls = that.data.liveImgs.file;
    wx.previewImage({
      urls: urls,
      current: e.currentTarget.id
    });

  },
  //==============================校验方法
  validateRequire: function (fieldValue, msg) {
    if (common.isEmpty(fieldValue)) {
      common.showToast(msg);
      return false;
    }
    return true;
  },

  /**
	 * 验证性别 必选
	 */
  validateGender: function () {
    var that = this;

    if (that.data.sex.length == 0) {
      console.log("sex ==" + that.data.sex);
      common.showToast("请勾选性别!");
      return false;

    }

    return true;
  },

  /**
	 * 验证服务工种 至少选一个
	 */
  validateServiceType: function () {
    var that = this;
    var index = 0;
    for (var i = 0; i < that.data.serviceTypes.length; i++) {
      if (that.data.serviceTypes[i].checked) {
        index++;
      }
    }
    if (index == 0) {
      common.showToast("请勾选服务工种!");
      return false;
    }
  },

  /**
	 * 工作经验 必选
	 */
  validateWorkYear: function () {
    var that = this;
    var index = 0;
    for (var i = 0; i < that.data.workYear.length; i++) {
      if (that.data.workYear[i].checked) {
        index++;
      }
    }
    if (index == 0) {
      common.showToast("请勾选工作经验!");
      return false;
    }
    return true;

  },

  /**
	 * 服务区域 必选
	 */
  validateServerArea: function () {
    var that = this;
    var index = 0;
    for (var i = 0; i < that.data.serverArea.length; i++) {
      if (that.data.serverArea[i].checked) {
        index++;
      }
    }
    if (index == 0) {
      common.showToast("请勾选服务区域!");
      return false;
    }
    return true;

  },

  /**
	 * 证书 必选
	 */
  validateHasCert: function () {
    var that = this;
    var index = 0;
    for (var i = 0; i < that.data.hasCertData.length; i++) {
      if (that.data.hasCertData[i].checked) {
        index++;
      }
    }
    if (index == 0) {
      common.showToast("请勾选技能证书!");
      return false;
    }

    if (that.data.hasCert == true) {
      if (that.data.certData.length == 0) {
        common.showToast("请添加技能证书!");
        return false;
      }

      for (var i = 0; i < that.data.certData.length; i++) {
        var item = that.data.certData[i];
        var certName = item.certName;
        var certImgs = item.certImgs;
        if (common.isEmpty(certName) && !common.isEmpty(certImgs)) {
          common.showToast("请填写证书名称!");
          return false;
        }

        if (!common.isEmpty(certName) && common.isEmpty(certImgs)) {
          common.showToast("请添加证书图片!");
          return false;
        }
      }

    }


    return true;

  },

  //=====================================提交操作========
  /**
	 * 注册信息
	 */
  validateUpdate: function (e) {
    var that = this;
    console.log("reg");
    console.log(that.data);
    var params = e.detail.value;

    //头像上传
    if (that.validateRequire(that.data.headImg, "请选择头像图片!") == false) return false;
    // 姓名校验
    if (that.validateRequire(e.detail.value['name'], "请填写姓名!") == false) return false;
    var name = e.detail.value['name'].trim();

    //籍贯校验
    if (that.validateRequire(that.data.region[0], "请选择籍贯!") == false) return false;

    // 身份证校验
    if (that.validateRequire(e.detail.value['idCard'], "请填写身份证号!") == false) return false;
    var idCard = e.detail.value['idCard'].trim();
    if (common.validateIdCard(idCard) == false) {
      common.showToast("身份证号不正确!");
      return false;
    }
    // 性别必选
    if (that.validateGender() == false) return false;

    // 服务工种必选
    if (that.validateServiceType() == false) return false;

    // 工作经验必选
    if (that.validateWorkYear() == false) return false;

    // 服务区域必须
    if (that.validateServerArea() == false) return false;

    //证书必选
    if (that.validateHasCert() == false) return false;

    that.doUpate(e.detail.value);
  },



  doUpate: function (formData) {
    var that = this;
    var params = {};
    params.resumeNo = wx.getStorageSync('resumeNo');
    //姓名
    params.name = formData['name'];
    //手机号
    params.mobile = wx.getStorageSync('mobile');
    //身份证号
    params.idCard = formData['idCard'];
    //常住地址
    params.addr = formData['addr'];
    //服务空档期
    params.serviceCanDate = formData['serviceCanDate'];

    //籍贯
    params.hukou = that.data.region[0] + " " + that.data.region[1];

    //性别
    params.sex = formData['sex'];

    //服务工种
    params.serviceTypes = formData['serviceTypes'].toString();

    //工作经验
    params.workYear = formData['workYear'];

    //服务区域
    params.regionids = formData['regionIds'];

    //自我介绍
    params.remark = formData['remark'];

    params.fromMobile = wx.getStorageSync('mobile');
    params.fromName = wx.getStorageSync('name');;

    console.log(params);

    //签名
    params = sign.getSignParams(params);

    wx.request({
      url: app.globalData.baseUrl + '/api/resume/update.json',
      data: params,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: function (res) {
        if (res.data.status == 999) {
          common.showToast(res.data.msg);
          return false;
        }

        var resumeData = res.data.data;

        wx.setStorageSync("resumeNo", resumeData.resumeNo);
        wx.setStorageSync("name", resumeData.resumeNo);
        wx.setStorageSync("total", resumeData.resumeNo);
        wx.setStorageSync("rowNum", resumeData.resumeNo);
        wx.setStorageSync("totalScore", resumeData.resumeNo);

        //进行图片上传
        that.checkUploadImg();

        //证书信息提交
        that.updateCert();

//        common.showToast("保存成功.");
        
        wx.showModal({
        	  title: '提示',
        	  content: '保存成功.',
        	  showCancel : false,
        	  success: function(res) {
        	    if (res.confirm) {
        	    	 	wx.reLaunch({
        	             url: '../index/index'
        	        })
        	    } else if (res.cancel) {
        	      console.log('用户点击取消')
        	    }
        	  }
        	});
        
       
       

      },
      fail: function (res) {

      },
      complete: function (res) { },
    })
  },

  checkUploadImg: function () {
    var that = this;
    //上传头像
    that.doHeadImg();

    //生活照片
    if (!common.isEmpty(that.data.liveImgs) && that.data.liveImgs.isSelect == true) {
      that.doUploadImg(that.data.liveImgs.file, "resume_live_img");
    }

    //身份证照片-正面
    if (!common.isEmpty(that.data.idCardFrontImg) > 0 && that.data.idCardFrontImg.isSelect == true) {
      that.doUploadImg(that.data.idCardFrontImg.file, "id_card_front_img");
    }

    //身份证照片-反面
    if (!common.isEmpty(that.data.idCardBackImg) && that.data.idCardBackImg.isSelect == true) {
      that.doUploadImg(that.data.idCardBackImg.file, "id_card_back_img");
    }
  },

  doHeadImg: function () {
    var that = this;
    console.log("doHeadImg");
    console.log(that.data.headImg.length);
    console.log(that.data.headImg.isSelect);
    if (!common.isEmpty(that.data.headImg) && that.data.headImg.isSelect == true) {
      console.log("ajax doHeadImg");
      var params = {};
      params.resumeNo = wx.getStorageSync("resumeNo");
      params.resourceType = "resume_head_img";
      params.canMulti = 0;
      wx.uploadFile({
        url: app.globalData.baseUrl + '/api/resume/upload_img.json',
        filePath: that.data.headImg.file[0],
        name: "imgs",
        formData: params,
        async: false,
        method: "POST",
        header: {
          'content-type': 'multipart/form-data'
        },
        success: function (res) {
          if (res.data.status == "999") {
            common.showToast(res.data.msg);
            return false;
          }
        }
      });
    }
  },

  doUploadImg: function (files, resourceType) {
	console.log("doUploadImg");
	console.log(resourceType);
    var that = this;
    if (common.isEmpty(files)) return false;
    var params = {};
    params.resumeNo = wx.getStorageSync("resumeNo");
    params.resourceType = resourceType;
    params.canMulti = 1;
    console.log(params);
    console.log("files.length = " + files.length);
    for (var i = 0; i < files.length; i++) {
    	 
      wx.uploadFile({
        url: app.globalData.baseUrl + '/api/resume/upload_img.json',
        filePath: files[i],
        name: "imgs",
        async: false,
        formData: params,
        method: "POST",
        header: {
          'content-type': 'multipart/form-data'
        },
        success: function (res) {
          if (res.data.status == "999") {
            common.showToast(res.data.msg);
            return false;
          }
          console.log("doUploadImg success");
        }
      });
    }
  },

  updateCert: function () {
    var that = this;
    var certData = that.data.certData;
    if (certData.length == 0) return false;
    for (var i = 0; i < certData.length; i++) {
      var item = certData[i];
      var params = {};
      params.resumeNo = wx.getStorageSync("resumeNo");
      params.certName = item.certName;
      if (item.id == 0) {
        wx.uploadFile({
          url: app.globalData.baseUrl + '/api/resume/add_cert.json',
          filePath: item.certImgs[0],
          name: "certImgs",
          async: false,
          formData: params,
          method: "POST",
          header: {
            'content-type': 'multipart/form-data'
          },
          success: function (res) {
            if (res.data.status == "999") {
              common.showToast(res.data.msg);
              return false;
            }
          }
        });
      }
    }
  },

  //================================视频类方法
  chooseVideo: function (res) {
    var that = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: function (res) {
        var file = res.tempFilePath;
        that.setData({
          chooseVideoFile: file
        });

        wx.showLoading({
          title: '正在上传视频',
          mask: true,
        });
        that.doUploadVideo(file);

      }
    })

  },

  doUploadVideo: function (file) {
    var that = this;
    var params = {};
    params = sign.getSignParams(params)
    wx.request({
      url: app.globalData.baseUrl + '/api/resume/up_token.json',
      data: params,
      success: function (res) {
        var result = res.data;
        console.log(result);
        if (result.status == 0) {
          var options = {
            uploadURL: 'https://upload-z1.qiniup.com', // 华北区
            //	        	          uptokenURL: app.globalData.baseUrl + '/api/resume/uptoken',
            uptoken: res.data.data,
            domain: 'http://v.jia-he-jia.com/',
            key: "resume-video-" + sign.createUuid()
          };

          qiniuUploader.upload(
            file,
            (res) => {
              wx.hideLoading()
              console.log("七牛云上传成功")
              console.log(res);
              var videoUrl = res.imageURL;
              that.doUpdateResumeVideoUrl(videoUrl);
            }, (error) => {
              console.error('error: ' + JSON.stringify(error));
              wx.hideLoading()
            }, options);
        }
      },
      fail: function (res) {
        wx.hideLoading()
      }


    })
  },

  doUpdateResumeVideoUrl: function (videoUrl) {
    var that = this;
    var params = {};
    params.resumeNo = wx.getStorageSync("resumeNo");
    params.videoUrl = videoUrl;
    params = sign.getSignParams(params);

    wx.request({
      url: app.globalData.baseUrl + '/api/resume/upload_video.json',
      data: params,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: function (res) {
        if (res.data.status == 999) {
          common.showToast(res.data.msg);
          return false;
        }

        console.log("保存人才视频url成功");
        that.getVideoUrlToken(videoUrl);
      },
      fail: function (res) {

      },
      complete: function (res) { },
    })
  },

  getVideoUrlToken: function (videoUrl) {
    var that = this;
    var params = {};

    params.videoUrl = videoUrl;
    params = sign.getSignParams(params);

    wx.request({
      url: app.globalData.baseUrl + '/api/resume/download_token.json',
      data: params,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'GET',
      success: function (res) {
        if (res.data.status == 999) {
          common.showToast(res.data.msg);
          return false;
        }

        var videoUrl = res.data.data;
        that.setData({ videoUrl: videoUrl });

      },
      fail: function (res) {

      },
      complete: function (res) { },
    })
  }


})